import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
 
/**
 * 获取表格最大高度
 * @param options
 * @returns {{tableRef: null, setTableHeight: setTableHeight, tableHeight: Ref<UnwrapRef<number>>}}
 */
export function useTableHeight(options = {}) {
  const { tableRef: externalTableRef = null, hasPagination = true } = options
 
  const internalTableRef = ref(null)
  const tableRef = externalTableRef || internalTableRef
  const maxHeight = ref(0)
 
  const calculateTableHeight = () => {
    if (!tableRef.value) return
    const windowHeight = window.innerHeight
    const tableTop = tableRef.value.$el.getBoundingClientRect().top
    const bottomPadding = hasPagination ? 70 : 20
    return windowHeight - tableTop - bottomPadding
  }
 
  const setTableHeight = () => {
    nextTick(() => {
      maxHeight.value = calculateTableHeight()
    })
  }
 
  onMounted(() => {
    window.addEventListener('resize', setTableHeight)
  })
 
  onUnmounted(() => {
    window.removeEventListener('resize', setTableHeight)
  })
 
  // 监听 tableRef 的变化
  watch(
    () => tableRef.value,
    (newVal) => {
      if (newVal && newVal.$el) {
        setTableHeight()
      }
    },
    { immediate: true }
  )
 
  // 提供手动触发方法
  const updateTableHeight = () => {
    nextTick(setTableHeight)
  }
 
  return {
    tableRef,
    maxHeight,
    setTableHeight,
    updateTableHeight
  }
}